package com.dzl.ocr;

import com.dzl.util.EmptyUtils;
import com.dzl.util.HttpUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WangJian
 * @date 2021/7/16 0016
 */
public class BaiduOcrUtils {

    /**
     * 获取百度智能云/文字识别的AccessToken
     * @date 2021/7/17 0017 15:24
     * @author wangjian
     * @param apiKey 百度智能云/文字识别的API Key
     * @param secretKey     百度智能云/文字识别的Secret Key
     * @return java.lang.String
     */
    public static String getOCRAccessToken(String apiKey, String secretKey) {
        String url="https://aip.baidubce.com/oauth/2.0/token";
        String param="grant_type=client_credentials"
                // 2. 百度智能云/文字识别的API Key
                + "&client_id="+apiKey
                // 3. 百度智能云/文字识别的Secret Key
                + "&client_secret="+secretKey;
        String result= HttpUtil.sendPost(url,param);
        if(result!=null&&!result.isEmpty()){
            AccessTokenBean bean = new Gson().fromJson(result, AccessTokenBean.class);
            String accessToken=bean.getAccess_token();
            return accessToken;
        }
        return null;
    }

    /**
     * 百度智能云/文字识别的通用文字识别
     * @date 2021/7/17 0017 15:24
     * @author wangjian
     * @param imageFilePath     图片文件路径
     * @param accessToken      百度智能云/文字识别的AccessToken
     * @return java.util.List<java.lang.String>
     */
    public static List<String> generalBasicOCR(String imageFilePath, String accessToken){
        List<String> retWords=new ArrayList<>();
        String url="https://aip.baidubce.com/rest/2.0/ocr/v1/form?access_token="+accessToken;
        String param="url="+imageFilePath;
        String result=HttpUtil.sendPost(url,param);
        if(result!=null&&!result.isEmpty()){
            OCRResultBean bean = new Gson().fromJson(result, OCRResultBean.class);
            List<OCRResultBean.VertexesLocation> words = null;
            if (EmptyUtils.isNotEmpty(bean.getForms_result())){
                if (EmptyUtils.isNotEmpty(bean.getForms_result().get(0).getHeader())){
                    words = bean.getForms_result().get(0).getHeader();
                }else if (EmptyUtils.isNotEmpty(bean.getForms_result().get(0).getBody())){
                    words =bean.getForms_result().get(0).getBody();
                }else if (EmptyUtils.isNotEmpty(bean.getForms_result().get(0).getFooter())){
                    words =bean.getForms_result().get(0).getFooter();
                }
            }
            if (EmptyUtils.isNotEmpty(words)){
                for(int i=0;i<words.size();i++){
                    String word=words.get(i).getWords();
                    retWords.add(word);
                }
            }
        }
        return retWords;
    }
}
